package com.magicsoft.app.helper;

import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.Environment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

public class Tool {
	Toast toast;
	Context mContext;
	ProgressDialog progressDialog;

	public Tool(Context context) {
		mContext = context;
		progressDialog = new ProgressDialog(mContext);
		progressDialog.setMessage("加载数据...");
		progressDialog.setOnKeyListener(new OnKeyListener() {

			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					progressDialog.dismiss();
				}
				return false;
			}
		});
		progressDialog.setCanceledOnTouchOutside(false);
	}

	public void showProgressDialog(Boolean isShow) {
		if (isShow) {
			progressDialog.show();
		} else {
			progressDialog.dismiss();
		}
	}
	
	public Boolean isProgressing() {
		if( progressDialog != null) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isCellphone(String str) {
		Pattern pattern = Pattern.compile("1[0-9]{10}");
		Matcher matcher = pattern.matcher(str);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}

	public void collapseSoftInputMethod(EditText editText) {
		InputMethodManager imm = (InputMethodManager) mContext
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	public static boolean hasSdcard() {

		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean IsVehiclenumber(String strnum) {
		Pattern pattern = Pattern
				.compile("^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$");
		Matcher matcher = pattern.matcher(strnum);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}

	public static String convertToUTF8(String str) {

		if (str != null) {
			str = URLEncoder.encode(str);
		} else {
			str = "";
		}

		return str;
	}

	public static SpannableString setLightTextView(String text, String light,
			int color) {
		Log.i("text:", text);
		Log.i("light:", light);
		Log.i("color:", color + "");

		SpannableString s = new SpannableString(text);

		Pattern p = Pattern.compile(light);

		Matcher m = p.matcher(s);

		while (m.find()) {
			int start = m.start();
			int end = m.end();
			Log.i("start-end", start + "-" + end);
			s.setSpan(new ForegroundColorSpan(color), start, end,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return s;
	}

	/**
	 * 检测是否存在sd卡
	 * 
	 * @return
	 */
	public final boolean checkSDcard() {
		boolean flag = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
		if (!flag) {
			Toast.makeText(mContext, "请插入手机存储卡再使用本功能", Toast.LENGTH_SHORT)
					.show();
		}
		return flag;
	}

	// Toast 显示消息
	public void showMessage(final String message) {

		if (toast != null) {
			toast.setText(message);
		} else {
			toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
		}
	}

	public void showProgressDialog(Boolean isShow, String message) {
		if (isShow) {
			progressDialog.setMessage(message);
			progressDialog.show();
		} else {
			progressDialog.dismiss();
		}
	}

	/**
	 * 将px值转换为dip或dp值，保证尺寸大小不变
	 * 
	 * @param pxValue
	 * @param scale
	 *            （DisplayMetrics类中属性density）
	 * @return
	 */
	public static int px2dp(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 将dip或dp值转换为px值，保证尺寸大小不变
	 * 
	 * @param dpValue
	 * @param scale
	 *            （DisplayMetrics类中属性density）
	 * @return
	 */
	public static int dip2px(Context context, float dpValue) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				dpValue, context.getResources().getDisplayMetrics());
	}

	/**
	 * 将px值转换为sp值，保证文字大小不变
	 * 
	 * @param pxValue
	 * @param fontScale
	 *            （DisplayMetrics类中属性scaledDensity）
	 * @return
	 */
	public static int px2sp(Context context, float pxValue) {

		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 将sp值转换为px值，保证文字大小不变
	 * 
	 * @param spValue
	 * @param fontScale
	 *            （DisplayMetrics类中属性scaledDensity）
	 * @return
	 */
	public static int sp2px(Context context, float spValue) {

		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
				spValue, context.getResources().getDisplayMetrics());
	}
	
	/**
	 * 判断字符串是否为数字
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9|.]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	// 数字是否两位小数
	public static boolean point2(String str) {
		Pattern pattern = Pattern.compile("[0-9]*(.[0-9]{0,2})?");
		Matcher ispoint2 = pattern.matcher(str);
		if (!ispoint2.matches()) {
			return false;
		}
		return true;
	}
	
	/**
	* 验证数字
	* 
	* @param 待验证的字符串
	* @return 如果是符合格式的字符串,返回 <b>true </b>,否则为 <b>false </b>
	*/
	public static boolean IsIntNumber(String str) {
		String regex = "^\\+?[0-9][0-9]*$";
		return str.matches(regex);
	}
	
	/**
	 * 在屏幕中央显示提示信息
	 * @param message
	 */
	public void showMsgCenter(final String message) {
		toast = Toast.makeText(mContext, message, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
}
